// 220902 liang 请求封装

//240703 yan 增加判断appId跳转到不同系统登录页
import { redirectLogin } from "./init";


// const baseURL = 'https://fszyrj.com/ZEDIY_WebApi_miniprogram',
// const baseURL = 'https://fszyrj.com/ZEDIY_WebApi_FTZT',  //方通103
// const baseURL = 'https://fszyrj.com/ZEDIY_WebApi_DIY',
//  const baseURL = 'http://103.40.192.150:19054',
//const baseURL = 'http://www.fszyrj.com/ZEDIY_WebApi_FTZT_AL',
// const baseURL = 'http://192.168.102.32:19117', //本地测试地址
const baseURL = 'https://www.fsftzt.com/ZEDIY_WebApi',  //方通阿里服务器
  // const baseURL = 'https://www.fsze.net/ZEDIY_WebApi', //新中尔阿里服务器
  //  const baseURL = 'https://www.fsftzt.com/ZEDIY_WebApi_1174',  //方通挖运阿里服务器
  // const baseURL = 'https://www.fsze.net/ZEDIY_WebApi_FSYC', //中尔阿里服务器友程接口
  // const baseURL = 'https://www.fsyczc.com/ZEDIY_WebApi_FSYC', //友程服务器友程接口

  // 线上使用
  http = {
    '1': '/api/v1/',
    '2': '/api/v2/',
    '3': '/api/v3/',
    '4': '/api/v4/',
    '5': '/api/v5/',
    '6': '/api/v6/',         // 财小白后端提供接口
  }
wx.setStorageSync('baseURL', baseURL)
//231208 yan 增加 refreshToken出错后直接用code换取登录
import { wxLogin } from "./login";

/**
 * 请求封装
 * @param {string} method HTTP 请求方法：OPTIONS/GET/HEAD/POST/PUT/DELETE/TRACE/CONNECT
 * @param {string} url 开发者服务器接口地址
 * @param {string|object|ArrayBuffer} data 请求的参数
 * @param {boolean} isShowErr 是否显示错误信息
 * @param {boolean} unDeal 是否先处理一下返回结果
 */
function request (method, url, data, isShowErr, unDeal) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseURL + url,
      data,
      header: {
        Authorization: `Bearer ${wx.getStorageSync('token')}`,
      },
      // timeout: 60000,    // 超时时间，单位为毫秒。默认值为 60000
      method,
      success: async (res) => {
        // console.log('接口封装 success', res);
        let isV6 = !(url.indexOf(http[6])),
          // root = res.data.root || {},
          root = !res.data ? {} : (res.data.root || {}), // 会计期管理页面 Account/cancel_charges_all_account_summary_v2、Account/charges_all_account_summary_v2 接口直接返回null
          errcode = '',
          errmsg = ''

        if (!isV6 && !unDeal) {
          try {
            errcode = root.errcode = root.response.errcode
            errmsg = root.errmsg = root.response.errmsg
          } catch (error) {
            console.log(url, res, error, res);
          }
        }

        // token 过期
        if (res.statusCode === 401) {
          await refreshToken()
          console.log('--- 刷新请求前的过期请求数量', exprReqNum);
          exprReqNum--
          console.log('刷新请求后的过期请求数量 ---', exprReqNum);
          // token刷新后重新进行请求，再将结果返回
          root = await request(...arguments)
        }
        // 财小白后端提供接口，仅返回，不作统一处理
        else if (isV6) {
          root = res.data
        }
        // 是否直接返回，不作统一处理，像 Entity_query_model/query_entity_query_model 接口，返回格式和其他不一样 40cm
        else if (unDeal) {
          root = res.data
        }
        // 非v6接口，接口返回不成功
        else if (errcode !== 0 && isShowErr) {
          wx.$toast(errmsg)
        }
        resolve(root)
      },
      fail: (err) => {
        reject();
        console.log('接口封装 fail', err);
      },
      complete: (res) => {

      },
    })
  })
}

// 刷新token
let refreshPromise = null,
  // token过期请求数量
  exprReqNum = 0
function refreshToken () {
  let post = {
    refresh_token: wx.getStorageSync('refresh'),
    system_id: wx.getStorageSync('system_id'),
  }
  let system_type = wx.getStorageSync('system_type');
  if (!refreshPromise || !exprReqNum) {
    refreshPromise = new Promise((resolve, reject) => {
      let url = '/pages/login/login';
      // if (system_type === 'WL') url = '/Logistics/Navigator/Navigator'
      // if (system_type === 'ZT') url = '/SlagCar/Login/Login';
      if (!post.refresh_token || !post.system_id) {
        exprReqNum = 0;
        let sysid = wx.getStorageSync('system_id')
        wxLogin(sysid).then((data) => {// 存储登录信息
          wx.$util.setLoginStorage(data)
          resolve();
        }, () => {
          redirectLogin();
          /*wx.reLaunch({
            url: '/pages/login/login',
            // url,  //231016 yan 修改不同系统跳转到不同登录页 231123 注销
          })*/
        })
        return
      }
      wx.$post(1, 'Authorize/RefreshToken', post, false).then(res => {
        console.log('刷新token接口返回数据', res);
        let { errcode, errmsg, } = res
        if (errcode !== 0) {
          exprReqNum = 0
          // -2/该刷新码无效，请重新登录  -4/该刷新码过期，请重新登录  8001001/有效期已过
          if ([-2, -4, 8001001,].includes(errcode)) {
            wx.$toast(errmsg).then(() => {
              let sysid = wx.getStorageSync('system_id')
              wxLogin(sysid).then((data) => {
                wx.$util.setLoginStorage(data)
                resolve();
              }, () => {
                redirectLogin();
                /*wx.reLaunch({
                  url,
                })*/
              })
            })
          }
          return
        }
        // 存储登录信息
        wx.$util.setLoginStorage(res.data.row[0])

        resolve()
      }, () => exprReqNum = 0)
    })
  }
  exprReqNum++
  return refreshPromise
}

// 221004 liang 上传文件专用接口
function uploadFile (filePath, name) {
  console.log(filePath, name);
  return new Promise((resolve, reject) => {
    // 参考 https://developers.weixin.qq.com/miniprogram/dev/api/network/upload/wx.uploadFile.html
    // https://www.jianshu.com/p/cbb99904ebd2
    let url = `${baseURL}${http[3]}Training_materials_attachments/upload_training_materials_attachments`
    if (name) url += `?file_name=${name}`
    wx.uploadFile({
      url: url,
      header: {
        Authorization: `Bearer ${wx.getStorageSync('token')}`,
      },
      filePath: filePath,
      name: 'file',
      formData: {
        // name: name || '',
        // value: {
        //   name: name || '',
        // },
        // filename: name || '',
      },
      success: async (res) => {
        let root = JSON.parse(res.data).root

        // token 过期
        if (res.statusCode === 401) {
          await refreshToken()
          exprReqNum--
          root = await uploadFile(filePath)
        }

        resolve(root)
      },
    })
  })
}

// get 请求
const get = (version, url, data, isShowErr = true, unDeal = false) => {
  return request('GET', `${http[version]}${url}`, data, isShowErr, unDeal)
}


const getNoV = (url, data, isShowErr = true, unDeal = false) => {
  return request('GET', `${url}`, data, isShowErr, unDeal)
}
// post 请求
const post = (version, url, data, isShowErr = true, unDeal = false) => {
  return request('POST', `${http[version]}${url}`, data, isShowErr, unDeal)
}
// put 请求
const put = (version, url, data, isShowErr = true, unDeal = false) => {
  return request('PUT', `${http[version]}${url}`, data, isShowErr, unDeal)
}
// delete 请求
const del = (version, url, data, isShowErr = true, unDeal = false) => {
  return request('DELETE', `${http[version]}${url}`, data, isShowErr, unDeal)
}

wx.$get = get
wx.$post = post
wx.$put = put
wx.$del = del
wx.$uploadReq = uploadFile
wx.$getNoV = getNoV
module.exports = {
  baseURL,
}


